/*
 * Copyright (C), 2014-2015, 杭州小卡科技有限公司
 * Created by ciwei@xiaokakeji.com on 2016/06/15.
 */
package com.micromall.utils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;

import java.io.IOException;
import java.io.Writer;
import java.text.SimpleDateFormat;

public class Jackson {

	private static ObjectMapper mapper;

	static {
		mapper = new ObjectMapper();
		// 属性排序，保证顺序生成JSON
		mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
		// 对于值为空的属性不生成
		mapper.setSerializationInclusion(Include.NON_NULL);
		mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
		// 输入时忽略JSON字符串中存在而Java对象实际没有的属性
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}

	public static <T> T readValue(String content, Class<T> valueType) {
		try {
			return mapper.readValue(content, valueType);
		} catch (IOException e) {
			throw new RuntimeException("Jackson 出异常了：", e);
		}
	}

	public static <T> T readValue(String content, TypeReference<?> valueTypeRef) {
		try {
			return mapper.readValue(content, valueTypeRef);
		} catch (IOException e) {
			throw new RuntimeException("Jackson 出异常了：", e);
		}
	}

	public static <T> T readValue(String content, JavaType valueType) {
		try {
			return mapper.readValue(content, valueType);
		} catch (IOException e) {
			throw new RuntimeException("Jackson 出异常了：", e);
		}
	}

	public static void writeValue(Writer w, Object value) {
		try {
			mapper.writeValue(w, value);
		} catch (IOException e) {
			throw new RuntimeException("Jackson 出异常了：", e);
		}
	}

	public static String writeValueAsString(Object value) {
		try {
			return mapper.writeValueAsString(value);
		} catch (IOException e) {
			throw new RuntimeException("Jackson 出异常了：", e);
		}
	}

}
